# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import time

from svn.core import SVN_DIRENT_TIME

import gvn.changebranch
import gvn.cmdline


helptext__gvn_changes = """changes: List changebranches.
usage: changes [--all | --user USERNAME]

Without --all or --user, list local changebranches.
"""


def Handle_GvnChanges(ctx):
  # TODO(epg): Make sure we don't hit the repository for simple 'gvn
  # changes'; that's a pure local operation.

  if ctx.options.verbose:
    fields = SVN_DIRENT_TIME
  else:
    fields = 0
  if ctx.options.all or ctx.options.user is not None:
    changes = gvn.changebranch.ListChangeBranches(ctx.project,
                                                  dirent_fields=fields,
                                                  user=ctx.options.user,
                                                  pool =ctx.pool)
    for (cname, dirent) in changes:
      if ctx.options.verbose:
        print '%s  %s' % (time.strftime('%F %T',
                                        time.localtime(dirent.time/1000000)),
                          cname)
      else:
        print cname
  else:
    # TODO(epg): Store snapshot time in ChangeState so we can be
    # verbose here, too.
    for change_name in set(x.change_name
                           for x in ctx.wc.change_state.itervalues()):
      print change_name

  return 0


gvn.cmdline.AddCommand('changes', Handle_GvnChanges, helptext__gvn_changes,
                       gvn.cmdline.AuthOptions(['all', 'user', 'project',
                                                'verbose']),
                       {'all':  'show all changebranches for this project',
                        'user': 'show all changebranches for user ARG'})
